layui.define(['layer', 'common', 'form', 'element', 'upload', 'util', 'table', 'md5'], function (exports) {

    var $ = layui.jquery
        , layer = layui.layer
        , table = layui.table
        , setter = layui.setter
        , md5 = layui.md5
        , common = layui.common;

    var success_code = 0, err_msg = "请求异常，请重试";
    var index;
    //全局的AJAX访问，处理AJAX清求时SESSION超时
    if (typeof($) != "undefined") {
        $.ajaxSetup({
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            complete: function (XMLHttpRequest, textStatus) {
                // 通过XMLHttpRequest取得响应头，sessionstatus
                var sessionstatus = XMLHttpRequest.getResponseHeader("sessionstatus");
                if (sessionstatus == "timeout") {
                    // 这里怎么处理在你，这里跳转的登录页面
                    common.showErrorTips("会话已过期,请重新登录", function () {
                        window.location.replace(XMLHttpRequest.getResponseHeader("redirectUrl"));
                    });
                }
            }
        });
    }
    var http = {
        param: function (data) {
            if (!data) return null;
            var array = new Array();
            for (var name in data) {
                var key = name;
                var value = data[name];
                if (value === null) {
                    continue;
                }
                if (Object.prototype.toString.call(value) === '[object Array]') {
                    var parent = key;
                    var children = value;
                    for (var i = 0; i < children.length; i++) {
                        var json = children[i];
                        if (Object.prototype.toString.call(json) === '[object Object]') {
                            for (var name in json) {
                                key = parent + '[' + i + '].' + name;
                                value = json[name];
                                if (value == null || value.length == 0) {
                                    continue;
                                }
                                key = encodeURIComponent(key);
                                value = encodeURIComponent(value);
                                array.push(key + '=' + value);
                            }
                        } else {
                            key = parent + '[' + i + ']';
                            key = encodeURIComponent(key);
                            value = encodeURIComponent(json);
                            array.push(key + '=' + value);
                        }
                    }
                } else if (Object.prototype.toString.call(value) === '[object Object]') {
                    var parent = key;
                    $.each(value, function (name, value) {
                        var tempKey = encodeURIComponent(parent + '.' + name);
                        var tempValue = encodeURIComponent(value);
                        array.push(tempKey + '=' + tempValue);
                    })
                } else {
                    key = encodeURIComponent(key);
                    value = encodeURIComponent(value);
                    array.push(key + '=' + value);
                }
            }
            return array.join('&');
        },
        ajaxGet: function (url, data, options, callback) {
            return $.ajax({
                type: 'get',
                data: data,
                url: url,
                async: options.async || false,
                success: callback
            });
        },
        ajaxPost: function (url, data, callback) {
            $.post(url, http.param(data), function (res) {
                if (res.code == success_code) {
                    callback || layer.msg(res.msg)
                }
            })
        },
        get: function (options) {
            options = options || {};
            options.loading = options.loading || false;
            options.loadingText = options.loadingText || '数据加载中,请稍候...';
            if (options.loading) {
                index = top.layer.msg(options.loadingText, {icon: 16, time: false, shade: 0.8});
            }
            return $.ajax({
                type: options.type || 'get',
                dataType: options.dataType || 'json',
                data: options.data || {},
                url: options.url,
                success: function (res) {
                    if (options.loading)
                        top.layer.close(index);
                    if (res.code == success_code) {
                        options.success && options.success(res);
                    } else {
                        layer.msg(res.msg || res.code, {shift: 6});
                        options.error && options.error();
                    }
                },
                error: function (e) {
                    if (options.loading)
                        top.layer.close(index);
                    layer.msg(err_msg, {shift: 6});
                    options.error && options.error(e);
                }
            });
        },
        post: function (options) {
            options = options || {};
            options.loadingText = options.loadingText || '数据加载中,请稍候...';
            if (options.loading) {
                index = top.layer.msg(options.loadingText, {icon: 16, time: false, shade: 0.8});
            }
            /*var index = top.layer.msg('数据提交中，请稍候',{icon: 16,time:false,shade:0.8});*/
            var s = localStorage.getItem("heartbeat");
            if (s) {
                return $.ajax({
                    type: options.type || 'post',
                    dataType: options.dataType || 'json',
                    data: http.param(options.data) || {},
                    url: options.url,
                    success: function (res) {
                        if (options.loading)
                            top.layer.close(index);
                        if (res.code == success_code) {
                            options.success && options.success(res);
                        } else {
                            layer.msg(res.msg || res.code, {shift: 6});
                            options.error && options.error();
                        }
                    },
                    error: function (e) {
                        if (options.loading)
                            top.layer.close(index);
                        layer.msg(err_msg, {shift: 6});
                        options.error && options.error(e);
                    }
                });
            } else {
                var key = options.url + options.data;
                key = $.md5(key);
                localStorage.setItem(key, JSON.stringify(options));
                if (options.loading)
                    top.layer.close(index);
                return options.success && options.success();
            }
        },
        table: function (options) {
            return table.render({
                elem: options.elem,
                url: options.url,
                method: options.type || 'get',
                cols: options.cols,
                page: options.page,
                skin: options.skin || 'line',
                limits: options.limits || [10, 20, 30, 40, 50],
                where: options.where || {},
                height: options.height || 315,
                even: options.even || false,
                loading: options.loading || true,
                done: options.done,
                response: {
                    statusName: 'code',
                    statusCode: success_code,
                    dataName: "rows",
                    countName: "total"
                },
                request: {
                    pageName: 'page', //页码的参数名称，默认：page,
                    limitName: 'pageSize' //每页数据量的参数名，默认：limit
                }
            });
        },
        location: function (href) {
            location.href = href;
        }
    };

    exports('http', http);
});